﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;
using System.IO;
using System.Xml;

namespace IntegrationPlatformMappingTool
{
    public partial class WorkItemTypePicker : Form
    {
        public delegate void WorkItemSelectedHandler(object sender, WorkItemPickerClosedEventArgs e);
        public event WorkItemSelectedHandler WorkItemSelected;

        private WorkItemTypeCollection _wic;
        private string _collectionURI;
        private WitLocation _witLocation;

        public WorkItemTypePicker()
        {
            InitializeComponent();
        }

        public WorkItemTypePicker(ProjectInfo project, TfsTeamProjectCollection collection, WitLocation location) : this()
        {
            WorkItemStore wis = (WorkItemStore)collection.GetService(typeof(WorkItemStore));
            _wic = wis.Projects[project.Name].WorkItemTypes;
            _collectionURI = string.Format("{0}/{1}", collection.Uri, project.Name);
            _witLocation = location;

            for (int i = 0; i < _wic.Count; i++)
            {
                lstWorkItemTypes.Items.Add(_wic[i].Name);
            }
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            string name = string.Empty;
            XmlDocument doc = new XmlDocument();

            for (int i = 0; i < _wic.Count; i++)
            {
                if (_wic[i].Name == lstWorkItemTypes.Items[lstWorkItemTypes.SelectedIndex].ToString())
                {
                    name = string.Format("{0}/{1}",_collectionURI, _wic[i].Name);
                    doc = _wic[i].Export(false);
                    break;
                }
            }

            OnWorkItemSelected(name, doc);
            Close();
        }

        protected void OnWorkItemSelected(string workitem, XmlDocument witd)
        {
            if (WorkItemSelected != null)
                WorkItemSelected(this, new WorkItemPickerClosedEventArgs(workitem, witd, _witLocation));
        }
    }
}
